/**
 * Created by apple on 16/11/15.
 */
/**
 * Created by apple on 16/11/14.
 */
var _theme_id_before = "";
var _theme_id_after = "";
var _name_before = "";
var _name_after = "";
var _img_before = "";
var _img_after = "";
var _input_id = "";
var data_articles = new Array();
var _info = "";

window.onload = function () {
    if (storage_admin_id) {
        articles_list();
        $('#dataTables-example').dataTable();
        $("#sideNav").click(function () {
            if ($(this).hasClass('closed')) {
                $('.navbar-side').animate({left: '0px'});
                $(this).removeClass('closed');
                $('#page-wrapper').animate({'margin-left': '260px'});

            }
            else {
                $(this).addClass('closed');
                $('.navbar-side').animate({left: '-260px'});
                $('#page-wrapper').animate({'margin-left': '0px'});
            }
        });
        $('.loading').hide();
    } else {
        window.location.href = "login.html"
    }
};

function articles_list() {
    $.ajax({
        type: 'GET',
        url: "http://118.178.59.93:8080/Motocycle/api/v1/themes/forback",
        async: false,
        success: function (data) {
            var obj = JSON.parse(data);
            try {
                if (obj.code == 0) {
                    var articles_list_total = "";
                    $.each(obj.data, function (i, item) {
                        articles_list_total += "<tr>" +
                            "<td class='article_theme_id'>" + item.theme_id + "</td>" +
                            "<td class='article_name'>" + item.name + "</td>" +
                            "<td class='article_img'>" +
                            "<img src=" + item.cover + " style='width: 150px;height: 80px;' data-id=" + item.theme_id + " class='carrousel_img'></td>" +
                            "<td>" + item.createdDate.substring(0, 11) + "</td>" +
                            "<td>" + item.article_count + "</td>" +
                            "<td>" +
                            "<span class='operation_button articles_delete' data-id=" + item.theme_id + " style='background: #337AEB;'>删除</span>" +
                            "<span class='operation_button articles_revise' data-id=" + item.theme_id + " style='background: #FF0100;'>修改</span>" +
                            "<span class='operation_button articles_save' data-id=" + item.theme_id + " style='background: #FFBB0C;display: none;'>保存</span>" +
                            "</td>" +
                            "</tr>"
                    });
                    $('#dataTables-example tbody').html(articles_list_total);
                }
            } catch (e) {

            }
        }
    })

}

//删除
$(document).on('click', '.articles_delete', function () {
    var data_id = $(this).attr('data-id');
    layer.msg('真的要删除该主题吗？', {
        time: 0, //不自动关闭
        btn: ['确定', '取消'],
        yes: function (index) {
            layer.close(index);
            $.ajax({
                type: 'DELETE',
                url: "http://118.178.59.93:8080/Motocycle/api/v1/themes/" + data_id,
                async: false,
                success: function (data) {
                    var obj = JSON.parse(data);
                    if (obj.code == 0) {
                        layer.msg('删除成功!');
                        setTimeout(function () {
                            location.reload();
                        }, 3000)
                    }
                }
            })
        }
    });
});


//修改
$(document).on('click', '.articles_revise', function () {
    //id可修改
    _theme_id_before = $(this).parents().parents('tr').find('.article_theme_id').html();
    $(this).parents().parents('tr').find('.article_theme_id').html("<input value=" + _theme_id_before + ">");
    //主题名字可修改
    _name_before = $(this).parents().parents('tr').find('.article_name').html();
    $(this).parents().parents('tr').find('.article_name').html("<input value=" + _name_before + ">");
    //上传图片
    _img_before = $(this).parents().parents('tr').find('.article_img img').attr('src');
    _input_id = $(this).parents().parents('tr').find('.article_img img').attr('data-id');
    $(this).parents().parents('tr').find('.article_img').append("<input type='file' id='file" + _input_id + "' data-id=" + _input_id + " style='margin:0 auto;width: 165px;' onchange='setImagePreview(this);'><label>(建议图片宽高比为375：80)</label>");
    //按钮变化
    $(this).parents().parents('tr').find('.articles_delete').hide();
    $(this).parents().parents('tr').find('.articles_revise').hide();
    $(this).parents().parents('tr').find('.articles_save').show();
});


//保存
$(document).on('click', '.articles_save', function () {
    _info = $(this).parents().parents('tr');
    _theme_id_after = _info.find('.article_theme_id input').val();
    _name_after = _info.find('.article_name input').val();
    _img_after = _info.find('.article_img img').attr('src');
    if (_theme_id_after == _theme_id_before) {
        if (_name_after == _name_before) {
            if (_img_after == _img_before) {
                //什么都没有修改
                $('.loading').hide();
                save_old_theme();
            } else {
                //只修改了图片
                data_articles = {cover: _img_after};
                save_new_theme();
            }

        } else {
            if (_img_after == _img_before) {
                //只修改了文件名
                data_articles = {name: _name_after}
                save_new_theme();
            } else {
                //修改了文件名+图片
                data_articles = {name: _name_after, cover: _img_after}
                save_new_theme();
            }
        }
    } else {
        if (_name_after == _name_before) {
            if (_img_after == _img_before) {
                //只修改了序号
                data_articles = {newtheme_id: _theme_id_after}
                save_new_theme();
            } else {
                //修改了序号+图片
                data_articles = {newtheme_id: _theme_id_after, cover: _img_after}
                save_new_theme();
            }
        } else {
            if (_img_after == _img_before) {
                //修改了序号+文件名
                data_articles = {newtheme_id: _theme_id_after, name: _name_after}
                save_new_theme();
            } else {
                //修改了序号+文件名+图片
                data_articles = {newtheme_id: _theme_id_after, name: _name_after, cover: _img_after}
                save_new_theme();
            }
        }
    }
});


//未修改任何东西情况下的保存
function save_old_theme() {
    layer.msg('您没有进行过任何修改,是否退出本次编辑？', {
        time: 0, //不自动关闭
        btn: ['确定', '取消'],
        yes: function (index) {
            layer.close(index);
            //id
            _info.find('.article_theme_id').html(_theme_id_after);
            //主题名字
            _info.find('.article_name').html(_name_after);
            //上传图片
            _info.find('.article_img').attr('src', _img_after);
            _info.find('.article_img input').remove();
            _info.find('.article_img label').remove();
            //按钮变化
            _info.find('.articles_delete').show();
            _info.find('.articles_revise').show();
            _info.find('.articles_save').hide();
            _info.find('.articles_delete').attr('data-id', _theme_id_after);
            _info.find('.articles_revise').attr('data-id', _theme_id_after);
            _info.find('.articles_save').attr('data-id', _theme_id_after);
        }
    });
}


//修改内容后的保存
function save_new_theme() {
    $.ajax({
        type: "PUT",
        url: "http://118.178.59.93:8080/Motocycle/api/v1/themes/" + _input_id,
        data: data_articles,
        async: false,
        success: function (data) {
            try {
                var obj = JSON.parse(data);
                if (obj.code == 0) {
                    //id
                    _info.find('.article_theme_id').html(_theme_id_after);
                    _info.find('.articles_delete').attr('data-id', _theme_id_after);
                    _info.find('.articles_revise').attr('data-id', _theme_id_after);
                    _info.find('.articles_save').attr('data-id', _theme_id_after);
                    //主题名字
                    _info.find('.article_name ').html(_name_after);
                    //上传图片
                    _info.find('.article_img img').attr('src', _img_after);
                    _info.find('.article_img input').remove();
                    _info.find('.article_img label').remove();
                    //按钮变化
                    _info.find('.articles_delete').show();
                    _info.find('.articles_revise').show();
                    _info.find('.articles_save').hide();

                    layer.msg("操作成功!", {time: 3000})
                }
            } catch (e) {
                layer.msg(data.msg, {time: 3000})
            }
        }
    })
}


//上传图片
function setImagePreview(file) {
    $('.loading').show();
    if (file.files && file.files[0]) {
        var postfix = file.files[0].name.split('.').pop();
        if (postfix != "jpg" && postfix != "gif" && postfix != "png" && postfix != "jpeg") {
            $('.loading').hide();
            layer.msg("上传仅支持：jpg,gif,png,jpeg格式")
        } else {
            var reader = new FileReader();
            var ratio = "";
            var ext = '.' + file.files[0].name.split('.').pop();
            reader.onload = function (evt) {
                //加载图片获取图片真实宽度和高度
                var image = new Image();
                image.onload = function () {
                    _img_width = image.width;
                    _img_height = image.height;
                    ratio = _img_width / _img_height;
                    //图片上传又拍云
                    var config = {
                        bucket: 'motorcycle',
                        expiration: parseInt((new Date().getTime() + 3600000) / 1000),
                        // 尽量不要使用直接传表单 API 的方式，以防泄露造成安全隐患
                        form_api_secret: '0jWegIsJu9xVxJMrgp4ydONAxok='
                    };
                    var instance = new Sand(config);
                    instance.upload("Image/" + parseInt((new Date().getTime() + 3600000) / 1000) + "Width" + _img_width + "AspectRatioBegin" + ratio + "AspectRatioEnd" + ext);

                };
                image.src = evt.target.result;
            };
            reader.readAsDataURL(file.files[0]);
        }
    } else {
        $('.loading').hide();
    }

}


document.addEventListener('uploaded', function (e) {
    for (var key in e.detail) {
        if (key === 'path') {
            var img_url = "http://motorcycle.b0.upaiyun.com" + e.detail[key];
            $('.article_img img').each(function (i, item) {
                var _id = $(this).attr('data-id');
                if (_input_id == _id) {
                    $(this).attr('src', img_url);
                    $('.loading').hide();
                }
            });

        }

    }
});




